<?php

/**
 * OrangeHRM is a comprehensive Human Resource Management (HRM) System that captures
 * all the essential functionalities required for any enterprise.
 * Copyright (C) 2006 OrangeHRM Inc., http://www.orangehrm.com
 *
 * OrangeHRM is free software; you can redistribute it and/or modify it under the terms of
 * the GNU General Public License as published by the Free Software Foundation; either
 * version 2 of the License, or (at your option) any later version.
 *
 * OrangeHRM is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
 * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * See the GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program;
 * if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
 * Boston, MA  02110-1301, USA
 */

if('ROOT_PATH'==ROOT_PATH){
	
}

require_once ROOT_PATH . '/lib/confs/sysConf.php';
require_once ROOT_PATH . '/lib/exception/ExceptionHandler.php';
require_once ROOT_PATH . '/lib/common/FormCreator.php';
require_once ROOT_PATH . '/lib/common/authorize.php';
require_once ROOT_PATH . '/lib/common/TemplateMerger.php';
require_once ROOT_PATH . '/lib/common/AjaxCalls.php';
require_once ROOT_PATH . '/lib/extractor/maintenance/EXTRACTOR_Rights.php';

require_once ROOT_PATH . '/lib/models/maintenance/UserGroups.php';
require_once ROOT_PATH . '/lib/models/maintenance/Users.php';
require_once ROOT_PATH . '/lib/models/maintenance/Rights.php';

require_once ROOT_PATH . '/lib/models/surveys/Answers.php';//Chinh Nguyen add

require_once ROOT_PATH . '/lib/models/surveys/Options.php';//Chinh Nguyen add
require_once ROOT_PATH . '/lib/models/surveys/Questions.php';//Chinh Nguyen add
require_once ROOT_PATH . '/lib/models/surveys/Surveys.php';//Chinh Nguyen add

require_once ROOT_PATH . '/lib/models/surveys/mail/MailSurvey.php';//Chinh Nguyen add


require_once ROOT_PATH . '/lib/extractor/surveys/EXTRACTOR_surveys.php';

require_once ROOT_PATH . '/lib/extractor/surveys/EXTRACTOR_questions.php';
require_once ROOT_PATH . '/lib/extractor/surveys/EXTRACTOR_answers.php';
require_once ROOT_PATH . '/lib/extractor/surveys/EXTRACTOR_options.php';



/**
 * Controller for recruitment module
 */
class SurveysController {

	private $authorizeObj;
//Get survey rights of logined user
	private $locRights;

    /**
     * Constructor
     */
    public function __construct() {
$rights = new Rights();
    	$this->locRights = $rights->getRights($_SESSION['userGroup'],'MOD011'); 
        if (isset($_SESSION) && isset($_SESSION['fname']) ) {
			$this->authorizeObj = new authorize($_SESSION['empID'], $_SESSION['isAdmin']);
        }
    }

    /**
     * Handle incoming requests
     * @param String code Recruit code
     */
    public function handleRequest($code) {

		if (empty($code) ) {
			trigger_error("Invalid Action " . $_GET['action'], E_USER_NOTICE);
			return;
		}
		/*
		$tempAction =null;
		if(!isset($_GET['action']))
			$tempAction ="List";
		else
			$tempAction= $_GET['action'];
		*/
		switch ($code) {
			
			case 'Surveys' :
				
				$viewListExtractor = new EXTRACTOR_newsList();

	            switch ($_GET['action']) {

	            	case 'Dashboard' :	                	
	                	$this->_viewDashBoard();	                  
	                    break;
	            	case 'SurveysSummary':
	            		$this->_viewSurveysSummary();
	            		break;
	            	case 'ShowResultsDetail':
	            		$surveyId = $_GET['id'];	                	
	                	$this->_viewSurveyResultsDetail($surveyId);	                  
	            		break;
	                case 'SurveyResults' :
	                	$surveyId = $_GET['id'];	                	
	                	$this->_viewSurveyResults($surveyId);	                  
	                    break;
	                case 'ShowPersonalResults':
	                	$surveyId = $_GET['surveyid'];
	                	$userId = $_GET['userid'];
	                	$this->_viewPersonalResultByUser($surveyId,$userId);
	                	break;
	                case 'viewPersonalResult';
	                	$surveyId = $_GET['id'];	                	
	                	$this->_viewPersonalResult($surveyId);	 
	                break;
	                case 'ListSurveysForUser';
	                	$this->_viewPublisList();
	                break;	                    
	                case 'List' :	                	
	                	$this->_viewListSurveys();	                  
	                    break;	             
	                 case 'Define' :
	                	$this->_viewDefine();
	                	break;
	                case 'DeleteSurveys' :
	                	$ids = $_POST['chkID'];
	                    $this->_deleteSurveys($ids);
	                break;
	                case 'CopySurveys' :
	                	$ids = $_POST['chkID'];
	                    $this->_copySurveys($ids);
	                break;
	                 case 'Questions' :
	                	$this->_viewListQuestions();
	                	break;
	                 case 'ViewAddQuestion':
	                 	$surveyid = $_GET['surveyid'];
	                 	$this->_viewAddQuestion(null,$surveyid);
	                	break;
	                 case 'AddQuestion':	                 
	                 	$questionExtractor = New EXTRACTOR_Questions();
	                 	$exArray = $questionExtractor->parseAddData($_POST);
	                 	$this->_addQuestion($exArray);
	                	break;
	                 case 'EditQuestion':
	                 	$questionExtractor = New EXTRACTOR_Questions();
	                 	$question = $questionExtractor->parseEditData($_POST);
	                 	$this->_updateQuestion($question);
	                 	break;
	                 case 'EditSurvey':
	                 	$surveyExtractor = New EXTRACTOR_Surveys();
	                 	$survey = $surveyExtractor->parseEditData($_POST);
	                 	$this->_updateSurvey($survey);
	                 	break;
	                 case 'ShowEditSurvey':
	                 	$id = $_GET['id'];
	                 	$this->_viewDefine($id);	                 
	                 	break;
	                 case 'ShowEditQuestion':
	                 	$id = $_GET['id'];
	                 	$this->_viewAddQuestion($id);	                 
	                 	break;
	                 case 'DeleteQuestions' :
	                	$ids = $_POST['chkID'];
	                    $this->_deleteQuestions($ids);
	                	break;
	                case 'AddOption';
	                	
	                	$optionExtractor = New EXTRACTOR_Options();
	                 	$option = $optionExtractor->parseAddData($_POST);
	                 	$this->_addOption($option);
	                	break;
					case 'Add' :
						//die("add survey");
						$surveyExtractor = new EXTRACTOR_Surveys();
						$survey = $surveyExtractor->parseAddData($_POST);
						$this->_addSurvey($survey);
						break;
					case 'SendInvitation':
						$id = $_GET['id'];	  
	                	$this->_sendInvitation($id);
						break;
					case 'Start' :	  
	                	$this->_viewListActive();	                  
	                    break;
	                case 'StartSurvey' :
	                	$id = $_GET['id'];	  
	                	$this->_viewSurveyProcess($id);	                  
	                    break;
	                case 'SubmitSurvey':	                	
	                	$answersExtractor = new EXTRACTOR_Answers();
	                	$answers = $answersExtractor->parseAddData($_POST);
	                	$this->_addAnswers($answers);
	                	break;			
	                case 'DeleteOptions' :
	                	$ids = $_POST['chkID'];
	                    $this->_deleteOptions($ids);
	                break;
	                
	            }
                break;

	    }
    }
	
	/**
	 * Generic method to display a list
	 * @param int $pageNumber Page Number
	 * @param int $count Total number of results
	 * @param Array $list results (in current page)
	 */

	private function _viewList($pageNumber, $count, $list) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/newsview.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['list'] = $list;
        $formCreator->popArr['count'] = $count;
        $formCreator->display();

	}
	
	private function _viewListByType($pageNumber, $count, $list,$type) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/newsview.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['list'] = $list;
        $formCreator->popArr['count'] = $count;
        $formCreator->popArr['type'] = $type;
        $formCreator->display();

	}
	
	private function _viewListAllByType($pageNumber, $countNews, $listNews,$typeNews, $countEvent, $listEvent,$typeEvent, $countAnnounce, $listAnnounce,$typeAnnounce,$countHot, $listHot,$typeHot) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/newsview.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['listNews'] = $listNews;
        $formCreator->popArr['countNews'] = $countNews;
        $formCreator->popArr['typeNews'] = $typeNews;
        
        $formCreator->popArr['listEvent'] = $listEvent;
        $formCreator->popArr['countEvent'] = $countEvent;
        $formCreator->popArr['typeEvent'] = $typeEvent;
        
        $formCreator->popArr['listAnnounce'] = $listAnnounce;
        $formCreator->popArr['countAnnounce'] = $countAnnounce;
        $formCreator->popArr['typeAnnounce'] = $typeAnnounce;
        
        $formCreator->popArr['listHot'] = $listHot;
        $formCreator->popArr['countHot'] = $countHot;
         $formCreator->popArr['typeHot'] = $typeHot;
        
        $formCreator->display();

	}
	
	
private function _viewListAllByTypePublic($pageNumber, $countNews, $listNews,$typeNews, $countEvent, $listEvent,$typeEvent, $countAnnounce, $listAnnounce,$typeAnnounce) {

        $formCreator = new FormCreator($_GET, $_POST);
        $formCreator->formPath = '/login.php';
        $formCreator->popArr['currentPage'] = $pageNumber;
        $formCreator->popArr['listNews'] = $listNews;
        $formCreator->popArr['countNews'] = $countNews;
        $formCreator->popArr['typeNews'] = $typeNews;
        
        $formCreator->popArr['listEvent'] = $listEvent;
        $formCreator->popArr['countEvent'] = $countEvent;
        $formCreator->popArr['typeEvent'] = $typeEvent;
        
        $formCreator->popArr['listAnnounce'] = $listAnnounce;
        $formCreator->popArr['countAnnounce'] = $countAnnounce;
        $formCreator->popArr['typeAnnounce'] = $typeAnnounce;
        $formCreator->display();

	}

	private function _viewListSurveys() {
		if(isset($_GET['page']))
			$page = $_GET['page'];
		else
			$page = 0;
		$surveys = Surveys::getPagingAll($page); 
		$totalSurveys = Surveys::getAll();
		//$records['surveys']= $surveys;
		$records['page']= $page;
		$records['surveys']= $surveys;
		$records['totalSurveys']= count($totalSurveys);
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/listSurveys.php";
		$template = new TemplateMerger($records, $path);
		$template->display();
	}
	
	private function _viewDashBoard() {
		$surveys = Surveys::getDashBoard(2); 
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/dashBoard.php";
		$template = new TemplateMerger($surveys, $path);
		$template->display();
	}
	
	private function _viewSurveyResults($surveyId) {
		$surveys = Surveys::getResults($surveyId);
		$survey =  $surveys[0];
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/surveyResults.php";
		$template = new TemplateMerger($survey, $path);
		$template->display();
	}
	
	public static function _viewPublicSurveyResults() {
		$surveys = Surveys::getPublicResults();
		return $surveys;
		//$survey =  $surveys[0];
		//$this->_authenticateViewLeaveDetails();
		//$path = "/templates/surveys/surveyResults.php";
		//$template = new TemplateMerger($surveys, $path);
		//$template->display();
	}
	
	private function _viewSurveyResultsDetail($surveyId) {
		$surveys = Surveys::getResults($surveyId);
		$survey =  $surveys[0];
		//$this->_authenticateViewLeaveDetails();
		if($survey->getSurveyType() != 2)
			$path = "/templates/surveys/surveyResults.php";
		else
			$path = "/templates/surveys/surveyQuizResults.php"; 
		$template = new TemplateMerger($survey, $path);
		$template->display();
	}
	
	
	private function _viewListActive() {
		$surveys = Surveys::getListActive(); 
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/startSurveys.php";
		$template = new TemplateMerger($surveys, $path);
		$template->display();
	}
	
	private function _sendInvitation($id){
		$survey = Surveys::getSurvey($id);
		$userArr = explode(",",$survey->getSurveyUsers());
		$sentArr = explode(",",$survey->getSurveySentEmail());
		$empArr = EmpInfo::getEmpInfo();
		for($j = 0; $j<count($empArr);$j++){
			if($survey->getSurveyOwner()==$empArr[$j][0]){
				$ownerEmail = $empArr[$j][6];
			}
		}
		$surveyName = $survey->getSurveyName();
		$emailContent = $survey->getSurveyEmailContent();
		$surveyOwner = EmpInfo::getFullName($survey->getSurveyOwner());
				
		$link = '<a href="http://'.$_SERVER['HTTP_HOST'].'/index.php?module=Home&menu_no=1&submenutop=SurveysModule&menu_no_top=surveys&id='.$id.'" target="rightMenu">'.$surveyName.'</a>';
		//$link ="1434";
		for($i = 0; $i<count($empArr);$i++){
			$surveyEmailContent = $emailContent;
			$to= array();
			if($survey->getSurveyResendEmail()==1){
				if(in_array($empArr[$i][0],$userArr)){
					$empName = $empArr[$i][1]." ".$empArr[$i][4]." ".$empArr[$i][3];
								
								
					$subject = "Survey Invitation Letter: $surveyName";
					
					$surveyEmailContent= str_replace("[USER]",$empName,$surveyEmailContent);
					$surveyEmailContent= str_replace("[SURVEY]",$link,$surveyEmailContent);
					$surveyEmailContent= str_replace("\n","<br/>",$surveyEmailContent);
					$body = "<html><body>";					
					$body .= "$surveyEmailContent";
					
					$body .= "<body><html>";			

					$email = new MailSurvey();
					//die("$surveyOwner <{$ownerEmail}>");
					$email->setMailFrom("$surveyOwner <{$ownerEmail}>");					
					$to[] = $empArr[$i][6];
					$email->setMail($body);
      				$email->setMailTo($to);
    				$email->setMailSubject($subject);
					if ($email->send()) {
						$_GET['message'] ="Message successfully sent!";
					} else {
						$_GET['message'] ="Message delivery failed...</p>";;
					}
					
				}
			}else{
				if(in_array($empArr[$i][0],$userArr) && !in_array($empArr[$i][0],$sentArr)){
						$empName = $empArr[$i][1]." ".$empArr[$i][4]." ".$empArr[$i][3];
						$subject = "Survey Invitation Letter:  $surveyName";
						$surveyEmailContent= str_replace("[USER]",$empName,$surveyEmailContent);
						$surveyEmailContent= str_replace("[SURVEY]",$link,$surveyEmailContent);
						$surveyEmailContent= str_replace("\n","<br/>",$surveyEmailContent);
						$body = "<html><body>";					
						$body .= $surveyEmailContent;
					
						$body .= "<body><html>";				
						
						$email = new MailSurvey();
						$email->setMailFrom("$surveyOwner <{$ownerEmail}>");		
						$to[] = $empArr[$i][6];
						$email->setMail($body);
      					$email->setMailTo($to);
    					$email->setMailSubject($subject);
						if ($email->send()) {
							$_GET['message'] ="Message successfully sent!";
						} else {
							$_GET['message'] ="Message delivery failed...</p>";;
						}		
				}
			}
		}
		$newSentEmail = array_unique(array_merge($userArr,$sentArr));
		$survey->setSurveySentEmail(implode(",",$newSentEmail));
		$survey->setSurveyActiveEmail(0);
		$survey->save();
		
		$this->_viewListSurveys();
		
	}
	
	private function _viewPublisList() {
		$surveys = Surveys::getPublicList(); 
		
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/listSurveysForUser.php";
		$template = new TemplateMerger($surveys, $path);
		$template->display();
	}
	
	private function _viewSurveysSummary() {
		$surveys = Surveys::getListActive(); 
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/surveysSummary.php";
		$template = new TemplateMerger($surveys, $path);
		$template->display();
	}
	
	
	
	private function _viewSurveyProcess($id) {
		//$answers = Answers::getAnswersBySurveyUser($id,$_SESSION['empID']);		
		$survey = Surveys::getSurvey($id);
		//if(count($answers)>0 && $survey->getSurveyType()==2)
		 	//return $this->_viewPersonalResult($id);
		$questions = Questions::getQuestionsBySurvey($id);
		$array['survey']= $survey;
		$array['questions']=$questions;
		
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/startSurveyProcess.php";
		$template = new TemplateMerger($array, $path);
		$template->display();
	}
	
	
	
	private function _viewPersonalResult($surveyId) {
		$survey = Surveys::getSurvey($surveyId);
		//die($survey->getSurveyType());
		if($survey->getSurveyType()==2){
		$questions = Questions::getQuestionsBySurvey($surveyId);		
		$array['survey']= $survey;
		$array['questions']=$questions;
		$array['userid']=$_SESSION['empID'];
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/personalResults.php";
		$template = new TemplateMerger($array, $path);
		$template->display();
		}else{
			//$userId= $_SESSION['empID'];
			$this->_viewSurveyResultsDetail($surveyId);
		}
	}
	
	private function _viewPersonalResultByUser($surveyId,$userId) {
		$survey = Surveys::getSurvey($surveyId);
		$questions = Questions::getQuestionsBySurvey($surveyId);		
		$array['survey']= $survey;
		$array['questions']=$questions;
		$array['userid']=$userId;
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/resultsByUser.php";
		$template = new TemplateMerger($array, $path);
		$template->display();
	}
	
	private function _viewListQuestions() {
		$questions = Questions::getAll(); 
		//$this->_authenticateViewLeaveDetails();
		$path = "/templates/surveys/listQuestions.php";
		$template = new TemplateMerger($questions, $path);
		$template->display();
	}
    
	private function _viewDefine($id=null) {
		if ($this->locRights['add']||$this->authorizeObj->isAdmin()) {
	    	$this->_editSurvey($id);
	    } else {
            $this->_notAuthorized();
		}
	}
	
	private function _viewAddQuestion($id=null,$surveyid=null) {
		if ($this->locRights['view']||$this->authorizeObj->isAdmin()) {
	    	$this->_editQuestion($id,$surveyid);
	    } else {
            $this->_notAuthorized();
		}
	}


    
	private function _editSurvey($id = null) {

		$path = '/templates/surveys/defineSurveys.php';

		try {
			
			if (empty($id)) {
				$survey = new Surveys();
				$questions =null;
			} else {
				$survey = Surveys::getSurvey($id);
				$questions = Questions::getQuestionsBySurvey($id);
			}
			$objs['survey_id'] = $id;
			$objs['survey_name'] = $survey->getSurveyName();
			$objs['survey_description'] = $survey->getSurveyDescription();
			$objs['survey_from_date'] = $survey->getSurveyFromDate();
			$objs['survey_to_date'] = $survey->getSurveyToDate();
			$objs['survey_thanks'] = $survey->getSurveyThanks();
			$objs['survey_active'] = $survey->getSurveyActive();
			$objs['survey_owner'] = $survey->getSurveyOwner();			
			$objs['survey_type'] = $survey->getSurveyType();
			$objs['results_view'] = $survey->getSurveyResultsView();
			$objs['survey_users'] = $survey->getSurveyUsers();
			$objs['survey_email_content'] = $survey->getSurveyEmailContent();
			$objs['survey_resend_email'] = $survey->getSurveyResendEmail();
			$objs['survey_sent_email'] = $survey->getSurveySentEmail();
			$objs['survey_active_email'] = $survey->getSurveyActiveEmail();
			
			
		
			$array['survey']= $objs;
			$array['questions']=$questions;
			$template = new TemplateMerger($array, $path);
			$template->display();
		} catch (NewsException $e) {
			$message = 'Operation Failed';
            $this->redirect($message);
		}
    }
    
	private function _editQuestion($id = null,$surveyid =null) {
		if(empty($id))
			$path = '/templates/surveys/addQuestion.php';
		else 
			$path = '/templates/surveys/editQuestion.php';
		try {			
			if (empty($id)) {
				$question = new Questions();
				$question->setSurveyId($surveyid);
			} else {
				$question = Questions::getQuestionById($id);
			}
			$objs['question_id'] = $id;
			$objs['question_text'] = $question->getText();
			$objs['survey_id'] = $question->getSurveyId();
			$objs['answer_type'] = $question->getAnswerType();
			//print_r($objs);
			$template = new TemplateMerger($objs, $path);
			$template->display();
		} catch (NewsException $e) {
			$message = 'Operation Failed';
            $this->redirect($message);
		}
    }

    
	private function _addSurvey($survey) {
		if ($this->locRights['add']||$this->authorizeObj->isAdmin()) {
			try {
				if(!Surveys::isNameExisted($survey->getSurveyName())){
					if($survey->getSurveyActive()==1 && count($survey->getSurveyUsers() >0))
						$survey->setSurveyActiveEmail(1);
					else
						$survey->setSurveyActiveEmail(0);	
					$survey->save();				
					$maxId = Surveys::getMaxId();				
		        	$message = 'Successfully Added';
		        	$URL = "CentralController.php?surveycode=Surveys&action=ShowEditSurvey&id=$maxId";
		        	$this->redirect($message,$URL);
				}else{					
					$message = 'Survey name is existed';
		        	$this->redirect($message);
				}
			} catch (SurveysException $e) {
				$message = 'Failed to Add';
	        	$this->redirect($message);
			}
		} else {
            $this->_notAuthorized();
		}

    }
    
	private function _addQuestion($array) {
		if ($this->locRights['add']||$this->authorizeObj->isAdmin()) {
			try {
				$existQuestions = Questions::getQuestionsExist($array['question']->getText(),$array['question']->getSurveyId());
				if(count($existQuestions)>0){
					//$message = "Question existed";
					//$this->redirect($message);
				}else{
				$array['question']->save();
				$maxId = Questions::getMaxId();
				if($array['options']!= null){
					for($i=0;$i<count($array['options']);$i++){	
						$array['options'][$i]->setQuestionId($maxId);				
						$array['options'][$i]->save();
					}
				}
	        	$message = 'Successfully Added';
	        	$surveyid = $array['question']->getSurveyId();	
	        	if($array['question']->getAnswerType()!=2 && $array['question']->getAnswerType()!=3 )
	        		$URL = "CentralController.php?surveycode=Surveys&action=ShowEditSurvey&id=$surveyid";
	        	else
	        		$URL = "CentralController.php?surveycode=Surveys&action=ShowEditQuestion&id=$maxId"; 
	        	//die($surveyid);
	        	$this->redirect($message,$URL);
				}
	        	//$this->_viewListQuestions();
	        	//echo "<script> window.history.go(-1); </script>\n";
				//exit ();
				

			} catch (SurveysException $e) {
				$message = 'Failed to Add';
	        	$this->redirect($message);
			}
		} else {
            $this->_notAuthorized();
		}

    }
    
	private function _updateQuestion($question) {
		if ($this->locRights['add']||$this->authorizeObj->isAdmin()) {
			try {
				$question->save();
				
				$surveyid = $question->getSurveyId();			
	        	$message = "Successfully Updated";
	        	$URL = "CentralController.php?surveycode=Surveys&action=ShowEditSurvey&id=$surveyid";
	        	//die($surveyid);
	        	$this->redirect($message,$URL);
	        	
	        	//$this->_viewListQuestions();
	        	//echo "<script> window.history.go(-1); </script>\n";
				//exit ();

			} catch (SurveysException $e) {
				$message = 'Failed to Add';
	        	$this->redirect($message);
			}
		} else {
            $this->_notAuthorized();
		}

    }	

    
	private function _updateSurvey($survey) {
		if ($this->locRights['edit']||$this->authorizeObj->isAdmin()) {
			try {
				$originalSurvey = Surveys::getSurvey($survey->getId());
				if((strtolower(str_replace(" ", "",trim($originalSurvey->getSurveyName()))) == strtolower(str_replace(" ", "",trim($survey->getSurveyName()))))){
					if(($originalSurvey->getSurveyUsers() == $survey->getSurveyUsers() && $survey->getSurveyResendEmail()==0))
						$survey->setSurveyActiveEmail(0);	
					if(($originalSurvey->getSurveyUsers() != $survey->getSurveyUsers() && $survey->getSurveyActive()==1)|| $survey->getSurveyResendEmail()==1)
						$survey->setSurveyActiveEmail(1);
								
					$survey->save();				
		        	$message = 'Successfully update';
		        	$maxId = $survey->getId();
			        $URL = "CentralController.php?surveycode=Surveys&action=ShowEditSurvey&id=$maxId";
			        $this->redirect($message,$URL);
				}else{
					if( !Surveys::isNameExisted($survey->getSurveyName())){
						if(($originalSurvey->getSurveyUsers() == $survey->getSurveyUsers() && $survey->getSurveyResendEmail()==0))
							$survey->setSurveyActiveEmail(0);
						if(($originalSurvey->getSurveyUsers() != $survey->getSurveyUsers() && $survey->getSurveyActive()==1)|| $survey->getSurveyResendEmail()==1)
							$survey->setSurveyActiveEmail(1);
										
						$survey->save();				
			        	$message = 'Successfully update';
			        	$maxId = $survey->getId();
			        	$URL = "CentralController.php?surveycode=Surveys&action=ShowEditSurvey&id=$maxId";
		        	$this->redirect($message,$URL);
					}else{					
						$message = 'Survey name is existed';
			        	$this->redirect($message);
					}
				}
				
			} catch (SurveysException $e) {
				$message = 'Failed to update';
	        	$this->redirect($message);
			}
		} else {
            $this->_notAuthorized();
		}

    }	
    
    
	private function _addOption($option) {
		if ($this->locRights['add']||$this->authorizeObj->isAdmin()) {
			try {
				if($option->getValue()==1){
					$question = Questions::getQuestionById($option->getQuestionID());
					if($question->getAnswerType()==2){
						$options = Options::getOptionsByQuestions($option->getQuestionID());
						foreach($options as $item){
							$item->setValue(0);
							$item->save();
						}	
					}
					
				}
				$option->save();
				$questionID = $option->getQuestionID();
				$message = 'Successfully Added';
				$URL = "CentralController.php?surveycode=Surveys&action=ShowEditQuestion&id=$questionID"; 
	        	//die($surveyid);
	        	$this->redirect($message,$URL);
				//echo "<script> window.history.go(-1); </script>\n";
				//exit ();			
			} catch (SurveysException $e) {
				$message = 'Failed to Add';
	        	$this->redirect($message);
			}
		} else {
            $this->_notAuthorized();
		}

    }
    
	private function _deleteOptions($ids) {
		if ($this->locRights['delete']||$this->authorizeObj->isAdmin()) {
				try {
					$optionId = $ids[0];
					$options = Options::getOptionsById($optionId);
					if(count($options)>0){
						$option = $options[0];
						$questionId = $option->getQuestionID();
						$count = Options::delete($ids);
	        			$message = 'Successfully Deleted';
	        			$URL = "CentralController.php?surveycode=Surveys&action=ShowEditQuestion&id=$questionId"; 
			        	//die($surveyid);
			        	$this->redirect($message,$URL);
					}
	        		
				} catch (newsException $e) {
					$message = 'Failed to Delete';
					$this->redirect($message);
				}
	           // echo "<script> window.history.go(-1); </script>\n";
				//exit ();
			} else {
	            $this->_notAuthorized();
			}
	    }
    
	private function _addAnswers($array) {		
		try {
			$count =0;
			for($i=0;$i<count($array);$i++){					
				$array[$i]->save();
				$count++;
			}
			if($count>0){
        	$message = 'Successfully Added';
        	$survey = Surveys::getSurvey($array[0]->getSurveyId());
        	if ($this->authorizeObj->isAdmin()) {
	        	if($survey->getSurveyType()==2)
	        		$this->_viewPersonalResult($survey->getId());
	        	else
	        	   	$this->_viewListSurveys();
        	}else{
        		if($survey->getSurveyType()==2)
	        		$this->_viewPersonalResult($survey->getId());
	        	else
	        	   	$this->_viewPublisList();
        	}
			}else{
				$message = 'Please select an answer';
        		$this->redirect($message);
			}

		} catch (SurveysException $e) {
			$message = 'Failed to Add';
        	$this->redirect($message);
		}

    }
	  
 	private function _deleteSurveys($ids) {
 		if ($this->locRights['delete']||$this->authorizeObj->isAdmin()) {
				try {
					
	        		$count = Surveys::delete($ids);
	        		$message = 'Successfully Deleted';
				} catch (newsException $e) {
					$message = 'Failed to Delete';
				}
	            $this->_viewListSurveys();
			} else {
	            $this->_notAuthorized();
			}
	    }
	
	private function _copySurveys($ids) {
		if ($this->locRights['add']||$this->authorizeObj->isAdmin()) {
			try {
        		for($i = 0; $i<count($ids);$i++){
        			$originalSurvey = Surveys::getSurvey($ids[$i]);
        			$newSurvey = new Surveys();
        			$str = 1;
        			while (Surveys::isNameExisted($originalSurvey->getSurveyName().$str)){
        				$str ++;
        			}
        			$newSurvey->setSurveyName($originalSurvey->getSurveyName().$str);
        			$newSurvey->setSurveyDescription($originalSurvey->getSurveyDescription());
        			$newSurvey->setSurveyFromDate($originalSurvey->getSurveyFromDate());
        			$newSurvey->setSurveyToDate($originalSurvey->getSurveyToDate());
        			$newSurvey->setSurveyThanks($originalSurvey->getSurveyThanks());
        			$newSurvey->setSurveyActive($originalSurvey->getSurveyActive());
        			$newSurvey->setSurveyOwner($_SESSION['empID']);
        			$newSurvey->setSurveyType($originalSurvey->getSurveyType());
        			$newSurvey->setSurveyResultsView($originalSurvey->getSurveyResultsView());
        			$newSurvey->setSurveyResendEmail($originalSurvey->getSurveyResendEmail());
        			if($originalSurvey->getSurveyActive()==1 && count($originalSurvey->getSurveyUsers() >0))
						$newSurvey->setSurveyActiveEmail(1);
					else
						$newSurvey->setSurveyActiveEmail(0);	
        			//$newSurvey->setSurveyActiveEmail($originalSurvey->getSurveyActiveEmail());
        			$newSurvey->save();
        			$maxSurveyId = Surveys::getMaxId();
        			$questions = Questions::getQuestionsBySurvey($ids[$i]);
        			if(count($questions)>0){
	        			foreach ($questions as $question){
	        				$newQuestion = new Questions();
	        				$newQuestion->setText($question->getText());
	        				$newQuestion->setSurveyId($maxSurveyId);
	        				$newQuestion->setAnswerType($question->getAnswerType());
	        				$newQuestion->save();
	        				$maxQuestionId = Questions::getMaxId();
	        				$options = Options::getOptionsByQuestions($question->getId());
	        				if(count($options)>0){
	        					foreach($options as $options){
	        						$newOption = new Options();
	        						$newOption->setQuestionId($maxQuestionId);
	        						$newOption->setText($options->getText());
	        						$newOption->setValue($options->getValue());
	        						$newOption->save();
	        					}
	        					
	        				}
	        			}        			
        			}
        		}
        		$message = 'Successfully copied';
			} catch (newsException $e) {
				$message = 'Failed to Delete';
			}
            $this->_viewListSurveys();
		} else {
            $this->_notAuthorized();
		}
	}
	    
	private function _deleteQuestions($ids) {
			if ($this->locRights['delete']||$this->authorizeObj->isAdmin()) {
				try {
	        		$count = Questions::delete($ids);
	        		$message = 'Successfully Deleted';
				} catch (newsException $e) {
					$message = 'Failed to Delete';
				}
	            echo "<script> window.history.go(-1); </script>\n";
				exit ();
			} else {
	            $this->_notAuthorized();
			}
	    }

    /**
   

	/**
	 * Redirect to given url or current page while displaying optional message
	 *
	 * @param String $message Message to display
	 * @param String $url URL
	 */
	public function redirect($message=null, $url = null) {

		if (isset($url)) {
			$mes = "";
			if (isset($message)) {
				$mes = "&message=";
			}
			$url=array($url.$mes);
			$id="";
		} else if (isset($message)) {
			preg_replace('/[&|?]+id=[A-Za-z0-9]*/', "", $_SERVER['HTTP_REFERER']);

			if (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0) {
				$message = "&message=".$message;
				$url = preg_split('/(&||\?)message=[A-Za-z0-9]*/', $_SERVER['HTTP_REFERER']);
			} else {
				$message = "?message=".$message;
			}

			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && !is_array($_REQUEST['id'])) {
				$id = "&id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		} else {
			if (isset($_REQUEST['id']) && !empty($_REQUEST['id']) && (preg_match('/&/', $_SERVER['HTTP_REFERER']) > 0)) {
				$id = "&id=".$_REQUEST['id'];
			} else if (preg_match('/&/', $_SERVER['HTTP_REFERER']) == 0){
				$id = "?id=".$_REQUEST['id'];
			} else {
				$id="";
			}
		}

		header("Location: ".$url[0].$message.$id);
	}

    /**
     * Show not authorized message
     */
    private function _notAuthorized() {
        trigger_error("Not Authorized!", E_USER_NOTICE);
    }
}

?>